package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Transactional
    @Override
    public OrderSubmitVO sumbitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());

        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        shoppingCartMapper.deleteAll(userId);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    @Override
    public String getTime(OrdersPaymentDTO ordersPaymentDTO) {
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        Orders orders = orderMapper.getByNumber(orderNumber);
        orders.setPayStatus(Orders.PAID);
        orderMapper.updatePayStatus(orders);
        return orders.getEstimatedDeliveryTime().toString();
    }

    @Override
    public PageResult page(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        Orders orders = Orders.builder()
                .status(status)
                .userId(BaseContext.getCurrentId())
                .build();
        Page<OrderDetailVO> p = (Page<OrderDetailVO>) orderMapper.getOrder(orders);
        for (OrderDetailVO o : p) {
            List<OrderDetail> list = orderDetailMapper.getByOrderId(o.getId());
            o.setOrderDetailList(list);
        }
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public OrderDetailVO getById(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        BeanUtils.copyProperties(orders, orderDetailVO);
        orderDetailVO.setOrderDetailList(orderDetailList);
        return orderDetailVO;
    }

    @Override
    public void cancelOrder(Long id) {
        orderMapper.updateStatus(id, Orders.CANCELLED);
    }

    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(null);
        orders.setPayStatus(Orders.UN_PAID);
        orderMapper.insert(orders);
    }

    @Autowired
    private UserMapper userMapper;

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

    /*
    //调用微信支付接口，生成预支付交易单
    JSONObject jsonObject = weChatPayUtil.pay(
            ordersPaymentDTO.getOrderNumber(), //商户订单号
            new BigDecimal(0.01), //支付金额，单位 元
            "苍穹外卖订单", //商品描述
            user.getOpenid() //微信用户的openid
    );
    */

        //生成空JSON, 跳过微信支付流程
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package")); // 这里的 key 应为 "package"

        return vo;
    }

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public void paySuccess(String orderNumber) {
        Orders orders = Orders.builder()
                .userId(BaseContext.getCurrentId())
                .payStatus(Orders.PAID)
                .status(Orders.TO_BE_CONFIRMED)
                .number(orderNumber)
                .build();
        orderMapper.update(orders);

        Long id = orderMapper.getByNumber(orderNumber).getId();

        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",id);
        map.put("content","订单号"+orderNumber);

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> p = (Page<Orders>) orderMapper.pageQurey(ordersPageQueryDTO);
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public OrderStatisticsVO statistics() {
        //根据订单类型计算总数

        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(orderMapper.countstatis(Orders.TO_BE_CONFIRMED))
                .confirmed(orderMapper.countstatis(Orders.CONFIRMED))
                .deliveryInProgress(orderMapper.countstatis(Orders.DELIVERY_IN_PROGRESS))
                .build();
        return orderStatisticsVO;
    }


    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.updateStatus(ordersConfirmDTO.getId(), Orders.CONFIRMED);
    }

    @Transactional
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //先判断是否为待接单状态
        Integer status = orderMapper.getStatusById(ordersRejectionDTO.getId());
        if (!Objects.equals(status, Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderMapper.updateStatus(ordersRejectionDTO.getId(), Orders.CANCELLED);
        //添加取消原因
        orderMapper.update(Orders.builder()
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .id(ordersRejectionDTO.getId())
                .build());
    }

    @Transactional
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //判断订单状态,待付款，待派送，已完成都可以进行取消操作
        Integer status = orderMapper.getStatusById(ordersCancelDTO.getId());
        Integer payStatus = orderMapper.getPayStatus(ordersCancelDTO.getId());
        if (Objects.equals(status, Orders.CANCELLED) || Objects.equals(payStatus, Orders.REFUND)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态，添加取消原因
        orderMapper.update(Orders.builder()
                .cancelReason(ordersCancelDTO.getCancelReason())
                .id(ordersCancelDTO.getId())
                .build());
        orderMapper.updateStatus(ordersCancelDTO.getId(), Orders.CANCELLED);
    }

    @Override
    public void delivery(Long id) {
        //判断订单是否为待派送状态
        Integer status = orderMapper.getStatusById(id);
        if (!Objects.equals(status, Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderMapper.updateStatus(id, Orders.DELIVERY_IN_PROGRESS);
    }

    @Override
    public void complete(Long id) {
        //判断订单是否为派送中状态
        Integer status = orderMapper.getStatusById(id);
        if (!Objects.equals(status, Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态为已完成
        orderMapper.updateStatus(id, Orders.COMPLETED);
        orderMapper.update(Orders.builder().deliveryTime(LocalDateTime.now()).build());
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
